const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
//格式化response
const response_formatter = require('./middlewares/response_formatter')
//引入log4js 工具

const logUtil = require('./utlis/log_utli')
//数据库的连接和数据表的建立
const sqldb = require('./db/mysqlDB');
sqldb.sequelize.sync({force: false}).then(function () {
    console.log("Server successed to start");
}).catch(function (err) {
    console.log("Server failed to start due to error: %s", err);
});

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
// app.use(response_formatter)

app.use(json())
// logger
app.use(async (ctx, next) => {
    const start = new Date()
    try {
        await next()
        const ms = new Date() - start
        logUtil.logResponse(ctx, ms)
    } catch (err) {
        const ms = new Date() - start
        logUtil.logError(ctx, err, ms)
    }
})

// routes
const AuthRouter = require('./routes/index').Auth;//用户授权

app.use(AuthRouter.routes(), AuthRouter.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
